﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;

namespace AuthenticationCenter.Utility
{
  public class CustomRSSJWTervice : ICustomJWTService
  {
    private readonly JWTTokenOptions _jwtTokenOptions;

    public CustomRSSJWTervice(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions)
    {
      this._jwtTokenOptions = jwtTokenOptions.CurrentValue;
    }
    public string GetToken(string UserName, string password)
    {
      Claim[] claims = new[] {
      new Claim(ClaimTypes.Name,UserName),
      new Claim(ClaimTypes.Role,"administrator")
      };
      string keyDir = Directory.GetCurrentDirectory();
      if (RSAHelper.TryGetKeyParameters(keyDir, true, out RSAParameters keyParams) == false)
      {
        keyParams = RSAHelper.GenerateAndSaveKey(keyDir);
      }

      SigningCredentials credentials = new SigningCredentials(new RsaSecurityKey(keyParams), SecurityAlgorithms.RsaSha256Signature);
      var token = new JwtSecurityToken(
      issuer: this._jwtTokenOptions.Issuer,
      audience: this._jwtTokenOptions.Audience,
      claims: claims,
      expires: DateTime.Now.AddMinutes(1),//
      signingCredentials: credentials);
      var hander = new JwtSecurityTokenHandler();
      return hander.WriteToken(token);
    }
  }
}
